<template>
  <div id="app">
    <el-card shadow="always">
      <!--这里是条件查询-->
      <el-form :inline="true" size="medium":model="studentSearch" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="studentSearch.sname" placeholder="学生姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="studentSearch.addr" placeholder="学生家庭住址"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="studentSearch.cid" placeholder="归属班级">
            <el-option label="全部班级" value="-1"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="find" icon="el-icon-search">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="addStudentRecord" icon="el-icon-plus">新增学生</el-button>
        </el-form-item>
      </el-form>
<!--这里是显示出的表格-->

      <el-table
          :data="studentList"
          style="width: 100%">
        <el-table-column
            label="学号"
            prop="sid"
            align="center"
            width="180">
        </el-table-column>
        <el-table-column
            label="姓名"
            align="center"
            prop="sname">
        </el-table-column>
        <el-table-column
            label="性别"
            align="center"
            prop="sex">
        </el-table-column>
        <el-table-column
            label="年龄"
            align="center"
            prop="age">
        </el-table-column>
        <el-table-column
            label="住址"
            align="center"
            prop="addr">
        </el-table-column>
        <el-table-column
            label="所在班级"
            align="center"
            prop="cname">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
<!--这里是分页插件-->
<!--带有@的事件，当相应事件发生相应的函数会触发，比如说点击事件-->
<!--带：的是绑定，可以双向绑定-->
<!--:page-sizes显示的是插件下面可以跳的页数，因为每页是5，用5的倍数比较符合常人使用习惯-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <!-- 修改学生信息的对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="isDialogOpen" :close-on-click-modal="false">
      <div class="student-form">
        <el-form :model="studentData" :rules="validationRules" ref="studentForm">
          <el-form-item label="姓名" prop="studentName" :label-width="formLabelWidth">
            <el-input v-model="studentData.studentName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender" :label-width="formLabelWidth">
            <el-radio-group v-model="studentData.gender">
              <el-radio :label="'男'">男</el-radio>
              <el-radio :label="'女'">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="年龄" prop="studentAge" :label-width="formLabelWidth">
            <el-input v-model.number="studentData.studentAge" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="住址" prop="homeAddress" :label-width="formLabelWidth">
            <el-input v-model="studentData.homeAddress" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="班级" prop="classId" :label-width="formLabelWidth">
            <el-select v-model="studentData.classId" placeholder="请选择班级">
              <el-option label="全部班级" :value="0"></el-option>
              <el-option v-for="cls in classOptions" :key="cls.id" :label="cls.name" :value="cls.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="saveStudentRecord">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import studentApi from '@/api/student'
import classesApi from "@/api/classes"
export default {
  data() {
    // 自定义校验规则：验证年龄
    const validateAge = (rule, value, callback) => {
      if (value === '' || value === null) {
        callback(new Error('年龄要有值'));
      } else if (!Number.isInteger(value)) {
        callback(new Error('年龄要为整数'));
      } else if (value < 1 || value > 150) {
        callback(new Error('年龄要在0-150,别太离谱了，没有不死族));
      } else {
        callback();
      }
    };
    return {
      studentList: [],      // 当前页的所有学生信息集合
      page:1,               // 当前页
      pageSize:5,           // 每页大小，page和pagesize在数据库Limit计算公式是（page-1)*pageSize,pageSize
      total:100,            // 总记录数
      studentSearch:{}, // 查询条件对象
      classesList:[],   // 全部班级列表
      dialogTitle: '编辑学生信息',
      isDialogOpen: false,
      studentData: {
        studentName: '',
        gender: '',
        studentAge: null,
        homeAddress: '',
        classId: ''
      },
      validationRules: {
        // 1. 校验学生姓名
        studentName: [
          {required: true, message: '请输入学生姓名', trigger: 'blur'},
        ],
        gender: [
          {required: true, message: '请选择性别', trigger: 'blur'},
        ],
        studentAge: [
          // { required: true, message: '请输入学生年龄', trigger: 'blur' },
          // 使用自定义验证规则验证年龄
          { validator : checkAge, trigger: 'blur'}
        ],
        homeAddress: [
          {required: true, message: '请输入学生住址', trigger: 'blur'},
        ],
        classId: [
          {required: true, message: '请选择学生班级', trigger: 'blur'},
        ]
      },
      formLabelWidth: '120px',
      classOptions: [] // 班级选项列表
    }
  },
  created() {

/*    // 1. 进行分页查询
    this.findByPage(this.page,this.pageSize)
    //2.查一下所有的班级在下拉列表中展示
    this.findClasses()*/
    this.find()
    this.findClasses()
    //this.findStudents()
  },

  methods: {
    // 查询一下所有学生
    async findStudents(){
      const {data:res} = await studentApi.findStudents()
      /*在控制台打印数据，这样好看出错误在哪*/
      console.log("分页数据：",res.data.list)
      if(res.code===200){
        /*这里如果成res.data前端能拿到数据，但解析不出来*/
        this.studentList = res.data.list
      }

    },
    // 进行分页查询
    async findByPage(page,pagesSize){
      // 若依框架写法：
      const {data:res} = await studentApi.findByPage(this.page,this.pageSize)
      console.log("分页数据2号：",res.data)
      if(res.code===200) {
        this.studentList = res.data.h.rows
        this.total = res.data.h.total
      }
    },

    //找出班级信息
    async findClasses(){
      const {data:res} = await classesApi.findClasses()
      console.log("这里打印班级的信息：",res.data)
      if(res.code===200) {this.classesList = res.data.list}
    },
    //带分页功能的条件查询
    async find(){
      const {data:res} = await studentApi.find(this.page,this.pageSize,this.studentSearch)
      if(res.code===200) {
        this.studentList = res.data.h.rows
        this.total = res.data.h.total
      }
    },
    //弹出对话框
    editStudent(){
      this.dialogFormVisible = true
    },



// 新增学生
    addStudentRecord() {
      // 修改对话框标题
      this.dialogTitle = "新增学生";
      // 清空表单
      this.currentStudent = {};
      // 显示对话框
      this.isDialogShown = true;
    },

//保存学生
    async saveStudentRecord(data) {
      // 验证表单数据
      const isValid = await this.$refs.ruleForm.validate();
      if (!isValid) {
        console.log("表单验证失败！");
        return;
      }

      let requestUrl = "/student/add"; // 默认为添加学生请求
      let requestMethod = "post"; // 默认请求方法为POST
      if (this.currentStudent.sid) {
        requestUrl = "/student/update"; // 如果存在sid，则为修改学生请求
        requestMethod = "put"; // 修改学生请求使用PUT方法
      }
      // 发送请求到后端
      try {
        const { data: response } = await studentApi.save(requestUrl, requestMethod, this.currentStudent);
        console.log("响应数据:", response);
        if (response.code === 200) {
          // 6.4 显示成功消息并关闭对话框
          this.$message({
            type: 'success',
            message: response.message,
            onClose: () => {
              this.isDialogShown = false;
              this.search(); // 重新查询数据
            }
          });
        } else {
          //发送错误消息
          this.$message({
            type: 'error',
            message: response.message
          });
        }
      } catch (error) {
        console.error("请求异常:", error);
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.find()


    },
    // 这个是当前页改变时事件
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.find()
      //this.findByPage(this.page,this.pageSize)
    },
    // 编辑学生
    editStudentInfo(idx, studentData) {
      this.dialogTitle = '编辑学生信息';
      this.currentStudent = { ...studentData };
      this.isDialogShown = true;

      console.log(idx, studentData);
    },
// 删除单个或多个学生
    deleteStudents(idx, studentData) {

      this.studentIdsToDelete = [];
      if (studentData) {
        this.studentIdsToDelete.push(studentData.sid);
      } else {
        this.studentIdsToDelete = this.selectedItems.map(item => item.sid);
      }
      // 弹出确认对话框
      this.$confirm(`确定要删除学号为${this.studentIdsToDelete.join(', ')}的学生吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // 确定删除
        studentApi.deleteStudent(this.studentIdsToDelete).then(({ data: response }) => {
          console.log("响应:", response);
          if (response.code === 200) {
            this.$message({
              type: 'success',
              message: response.message,
              onClose: () => {
                // 删除成功后重新加载数据
                this.search();
              }
            });
          } else {
            this.$message({
              type: 'error',
              message: response.message
            });
          }
        });
      }).catch(() => { // 取消删除
        this.$message({
          type: 'info',
          message: '已取消删除操作'
        });
      });
    }
  }
}
</script>
<style>
/*指定分页的位置和大小*/
.el-pagination{
  text-align: right;
  margin-top: 15px;
}
/*指定卡片的位置*/
  #app{
    display: flex;
    justify-content: center;
  }
/*指定elcard这个组件的宽度*/
.el-card{
  width: 90%;
}
</style>
